package cloudlean.zuul.fallback;

import cloudlean.zuul.filter.MdlResponseBody;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Project Name: cloud-learn
 * File Name: MdlFallbackProvider
 * Package Name: cloudlean.zuul.fallback
 * Date: 2018/7/9  15:57
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Component
@Slf4j
public class MdlFallbackProvider implements FallbackProvider {

    @Override
    public ClientHttpResponse fallbackResponse(Throwable cause) {
        if (cause != null && cause.getCause() != null) {
            String reason = cause.getCause().getMessage();
            //输出详细的回退原因
            log.info("fallback reason: {}",reason);
        }

        //此处自定义回退返回结构体,本利写了个单例应对多线程
        return new ClientHttpResponse(){
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(JSONObject.toJSONBytes((new MdlResponseBody("100007","服务错误，请求失败"))));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                //和body中的内容编码一致，否则容易乱码
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }

            /**
             * 网关向api服务请求是失败了，但是消费者客户端向网关发起的请求是OK的，
             * 不应该把api的404,500等问题抛给客户端
             * 网关和api服务集群对于客户端来说是黑盒子
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {

                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {

                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {

                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {


            }

        };

    }

    @Override
    public String getRoute() {
        return "*";//api服务id，如果需要所有调用都支持回退，则return "*"或return null
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return null;
    }

}
